package codeTop;

import java.util.Objects;
import java.util.Stack;

public class q224 {
    public int calculate(String s) {
        int n = s.length();
        Stack<Object> stack = new Stack<>();
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) != ' ') {
                if (Character.isDigit(s.charAt(i))) {
                    int num = 0;
                    while (i < n && Character.isDigit(s.charAt(i))) {
                        num = num*10+s.charAt(i)-'0';
                        i++;
                    }
                    i--;
                    if (!stack.empty() && stack.peek().equals('-')) {
                        stack.pop();
                        num = -num;
                    }
                    stack.push(num);
                } else if (s.charAt(i) == '('||s.charAt(i)=='-') {
                    stack.push(s.charAt(i));
                } else if (s.charAt(i) == ')') {
                    int num = 0;
                    while (!stack.peek().equals('(')) {
                        int pop = (int) stack.pop();
                        num+=pop;
                    }
                    stack.pop();
                    if (!stack.empty() && stack.peek().equals('-')) {
                        stack.pop();
                        num = -num;
                    }
                    stack.push(num);
                }
            }
        }
        int res = 0;
        while (!stack.isEmpty()) {
            res+=(int)stack.pop();
        }
        return res;
    }

    public static void main(String[] args) {
        q224 q = new q224();
        System.out.println(q.calculate(" 2-1 + 2 "));
    }
}
